# 2.py 循环式

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        head = ListNode()
        carry = 0
        node = head

        while(l1 or l2):
            new_node = ListNode(0)

            if l1 is None:
                sum_val = l2.val + carry
                new_node.val = sum_val % 10
                carry = sum_val // 10

            elif l2 is None:
                sum_val = l1.val + carry
                new_node.val += sum_val % 10
                carry = sum_val // 10

            else:
                sum_val = l1.val + l2.val + carry
                new_node.val += sum_val % 10
                carry = sum_val // 10

            if carry != 0:
                new_node.next = ListNode(val=carry)

            if l1 is not None:
                l1 = l1.next
            if l2 is not None:        
                l2 = l2.next
            node.next = new_node
            node = node.next

        return head.next